var PrintPurchaseOrder = function () {
  var template = /*html*/ `
    <div class="print-order" v-loading.fullscreen.lock="loading">
      <div style="height:40px">
        <el-button size="small" type="primary" @click="print">打印</el-button>
        <el-button size="small" type="primary" @click="sendEmail">发送至邮箱</el-button>
        <el-button size="small" v-if="hasSumBtn" type="primary" @click="isShowSum=!isShowSum">
          <span v-if="isShowSum">隐藏采购量小计</span>
          <span v-else>显示采购量小计</span>
        </el-button>
        <el-button size="small" v-if="hasImgBtn" type="primary" @click="isShowImg=!isShowImg">
          <span v-if="isShowImg">隐藏物料图片</span>
          <span v-else>显示物料图片</span>
        </el-button>
        <config-button v-if="tableColumns!==null" :config.sync="pageConfig" :table-columns="tableColumns">采购单设置</config-button>
      </div>
      <div class="print-order-div print-area" style="text-align:center" v-if="user!==null&&pageConfig.tableColumns!==undefined">
        <div class="print-order-content clearfix" :style="[pageSize]">
          <div style="float:left;width:100%;" ref="printArea">
            <div class="order-title" :style="[textSize.titleSize]">
              {{user.companyInfo.name}}
            </div>
            <div class="order-header" :style="[textSize.titleSize]">
              <template v-if="orderType===1">
                <span>订</span>
                <span style="margin-left:20px;">购</span>
                <span style="margin-left:20px;">单</span>
              </template>
              <template v-else>
                <span>库</span>
                <span style="margin-left:20px;">存</span>
                <span style="margin-left:20px;">采</span>
                <span style="margin-left:20px;">购</span>
                <span style="margin-left:20px;">单</span>
              </template>
              <div class="urgent" @click="urgentClick">
                <div class="urgent-checkbox">
                  <span v-if="isUrgent">√</span>
                </div>
                <div style="margin-left:5px;">加急</div>
              </div>
            </div>
            <div style="margin-top:-1px;">
              <table class="order-info-table" cellspacing="0" cellpadding="0" :style="[textSize.tableSize]">
                <colgroup>
                  <col style="width:90px">
                  <col style="width:180px">
                  <col style="width:90px">
                  <col style="width:180px">
                </colgroup>
                <tbody>
                  <tr>
                    <th>物料名称</th>
                    <td colspan="3">
                      <div class="order-type" style="line-height:1.2;text-align:left">
                        <template v-if="mode==='edit'">
                          <el-select v-model="orderSearch.materialName" style="margin-left:20px;width:110px;" size="small" @change="searchData" 
                            :clearable="true">
                            <el-option v-for="(item,index) in materialNameList" :key="'materialName_'+index"
                              :value="item" :label="item"></el-option>
                          </el-select>
                        </template>
                        <template v-else>
                          <div style="margin-left:20px;width:110px;padding-left:15px;display:inline-block;text-align:left">
                            {{orderSearch.materialName}}
                          </div>
                        </template>
                        <div style="margin-left:10px;border:1px solid #000000;width:13px;height:13px;display:inline-block;">
                        </div>
                        <span v-if="orderType===1">订单采购</span>
                        <span v-else>库存采购</span>
                        <div style="margin-left:5px;display:inline-block;">
                          <input v-if="mode==='edit'" v-model="printOrderNo" style="width:12em;" :style="[textSize.tableSize]" maxlength="20" placeholder="请输入采购单号">
                          <span v-else>{{printOrderNo}}</span>
                        </div>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <th>供应商</th>
                    <td>
                      <template v-if="mode==='edit'">
                        <el-select class="curstomer-select" v-model="orderSearch.curstomerId" style="width:175px;" size="small" @change="curstomerChange">
                          <el-option v-for="curstomer in curstomerList" :key="'curstomer_'+curstomer.id"
                            :value="curstomer.id" :label="curstomer.customerName"></el-option>
                        </el-select>
                      </template>
                      <template v-else>
                        <span>{{selectCurstomer.customerName}}</span>
                      </template>
                    </td>
                    <th>订货日期</th>
                    <td>
                      <template v-if="mode==='edit'">
                        <el-date-picker class="order-date-picker" v-model="orderTime" format="yyyy-MM-dd" value-format="timestamp" size="small" 
                          :clearable="false" :editable="false" style="width:175px;"></el-date-picker>
                      </template>
                      <template v-else>
                        <span>{{moment(orderTime).format('YYYY-MM-DD')}}</span>
                      </template>
                    </td>
                  </tr>
                  <tr>
                    <th>联系电话</th>
                    <td>{{selectCurstomer.phone}}</td>
                    <th>交货日期</th>
                    <td>
                      <template v-if="deliveryEdit && mode==='edit'">
                        <el-date-picker class="order-date-picker" v-model="deliveryTime" format="yyyy-MM-dd" value-format="timestamp" size="small" 
                          :clearable="false" style="width:175px;"></el-date-picker>
                      </template>
                      <template v-else>
                        <span v-if="deliveryTime!==null">{{moment(deliveryTime).format('YYYY-MM-DD')}}</span>
                      </template>
                    </td>
                  </tr>
                  <tr>
                    <th>传真</th>
                    <td>{{selectCurstomer.fax}}</td>
                    <th>下单人</th>
                    <td :contenteditable="mode==='edit'">{{user.userName}}</td>
                  </tr>
                  <tr>
                    <th>联系人</th>
                    <td>{{selectCurstomer.contact}}</td>
                    <th>联系电话</th>
                    <td>{{user.phone}}</td>
                  </tr>
                  <tr v-if="showEmail">
                    <th>邮箱地址</th>
                    <td>{{selectCurstomer.email}}</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div class="print-order-detail">
              <table class="print-order-detail-table" cellspacing="0" cellpadding="0" :style="[textSize.tableSize]">
                <colgroup>
                  <template v-for="tableColumn in pageConfig.tableColumns">
                    <col :key="'col_'+tableColumn.id" :style="{width:tableColumn.width+'px'}">
                  </template>
                </colgroup>
                <tr v-if="pageConfig.showTableHead">
                  <th v-for="tableColumn in pageConfig.tableColumns" :key="'head_'+tableColumn.id">
                    <span>{{tableColumn.label}}</span>
                    <div v-if="tableColumn.hasSort&&mode==='edit'" class="sort-caret" :class="[tableColumn.sortType]">
                      <div class="sort-index">{{getSortIndex(tableColumn)}}</div>
                      <i class="ascending" @click="toOrderData(tableColumn,'ascending')"></i>
                      <i class="descending" @click="toOrderData(tableColumn,'descending')"></i>
                    </div>
                  </th>
                </tr>
                <template v-for="(orderGroup,groupIndex) in orderGroups">
                  <template v-for="(order,index) in orderGroup.orders">
                    <tr :key="'image_'+order._id" v-if="isShowImg&&order.img!==null">
                      <td :colspan="pageConfig.tableColumns.length" class="order-image">
                        <img :src="formatImgUrl(order.img)">
                      </td>
                    </tr>
                    <tr :key="'order_'+order._id">
                      <td v-for="(tableColumn,colIndex) in pageConfig.tableColumns" :key="'data_'+tableColumn.id">
                        <div v-if="!tableColumn.config.edit" style="height:100%;" :style="[getAlignStyle(tableColumn)]">
                          {{getTableData(order,tableColumn,index)}}
                        </div>
                        <div v-else>
                          <show-textarea v-if="mode==='edit'" class="orderTextarea" v-model="order[tableColumn.config.field]" :autosize="true">
                          </show-textarea>
                          <div v-else v-html="formatShowData(order[tableColumn.config.field])" :style="[getAlignStyle(tableColumn)]">
                          </div>
                        </div>
                        <template v-if="colIndex===0&&addRowRemark">
                          <div class="add-row" v-if="mode==='edit'" @click="changeRowRemark(order)">
                            <i v-if="!order._hasRow" class="el-icon-plus" title="显示行备注"></i>
                            <i v-else class="el-icon-minus" title="隐藏行备注"></i>
                          </div>
                        </template>
                        <template v-if="colIndex===pageConfig.tableColumns.length-1&&addDelRow">
                          <div class="deleteBtn" v-if="mode==='edit'" @click="deleteRow(order)">删除</div>
                        </template>
                      </td>
                    </tr>
                    <tr v-if="order._hasRow" :key="'rowRemark_'+order._id">
                      <td :colspan="pageConfig.tableColumns.length" style="text-align:left;">
                        <show-textarea v-if="mode==='edit'" class="rowRemark" v-model="order.rowRemark" :autosize="true">
                        </show-textarea>
                        <div v-else v-html="formatShowData(order.rowRemark)">
                        </div>
                      </td>
                    </tr>
                  </template>
                  <tr :key="'sum_'+groupIndex" v-if="isShowSum">
                    <td :colspan="pageConfig.tableColumns.length">
                      <div style="text-align:right;padding-right:20px;">
                        采购量小计：{{orderGroup.sum}}
                      </div>
                    </td>
                  </tr>
                </template>
              </table>
            </div>
            <div style="margin-top:15px;text-align:left;" :style="[textSize.otherSize]">
              <div>交易条款：</div>
              <div style="padding-left:3em">
                <div class="vue-rich-editor" v-html="clauseContent"></div>
              </div>
            </div>
            <div class="clearfix page-floor" :style="[textSize.otherSize]">
              <div style="float:left;width:38%;">
                <div class="input-label clearfix">
                  <div style="width:3.5em">供方：</div>
                  <show-textarea v-if="mode==='edit'" class="floor-input" style="width:calc(100% - 4em)" v-model="supplier" :autosize="true"
                    :style="[textSize.otherSize]"></show-textarea>
                  <div v-else class="floor-input" style="width:calc(100% - 4em)" :style="[textSize.otherSize]" v-html="formatShowData(supplier)"></div>
                </div>
                <div class="input-date clearfix">
                  <div style="width:3.5em">日期：</div>
                  <input v-if="mode==='edit'" v-model="supplierDate.year" style="width:60px;text-align:right;" maxlength="4" :style="[textSize.otherSize]">
                  <div v-else style="width:62px;height:18px;text-align:right;">{{supplierDate.year}}</div>
                  <div>年</div>
                  <input v-if="mode==='edit'" v-model="supplierDate.month" style="width:40px;text-align:center;" maxlength="2" :style="[textSize.otherSize]">
                  <div v-else style="width:42px;height:18px;text-align:right;">{{supplierDate.month}}</div>
                  <div>月</div>
                  <input v-if="mode==='edit'" v-model="supplierDate.day" style="width:40px;text-align:center;" maxlength="2" :style="[textSize.otherSize]">
                  <div v-else style="width:42px;height:18px;text-align:right;">{{supplierDate.day}}</div>
                  <div>日</div>
                </div>
              </div>
              <div style="float:right;width:42%;">
                <div class="input-label clearfix">
                  <div style="width:3.5em">购方：</div>
                  <show-textarea v-if="mode==='edit'" class="floor-input" style="width:calc(100% - 4em)" v-model="user.companyInfo.name" :autosize="true"
                    :style="[textSize.otherSize]"></show-textarea>
                  <div v-else class="floor-input" style="width:calc(100% - 4em)" :style="[textSize.otherSize]" v-html="formatShowData(user.companyInfo.name)"></div>
                </div>
                <div class="input-date clearfix">
                  <div style="width:3.5em">日期：</div>
                  <input v-if="mode==='edit'" v-model="curstomerDate.year" style="width:60px;text-align:right;" maxlength="4" :style="[textSize.otherSize]">
                  <div v-else style="width:62px;height:18px;text-align:right;">{{curstomerDate.year}}</div>
                  <div>年</div>
                  <input v-if="mode==='edit'" v-model="curstomerDate.month" style="width:40px;text-align:center;" maxlength="2" :style="[textSize.otherSize]">
                  <div v-else style="width:42px;height:18px;text-align:right;">{{curstomerDate.month}}</div>
                  <div>月</div>
                  <input v-if="mode==='edit'" v-model="curstomerDate.day" style="width:40px;text-align:center;" maxlength="2" :style="[textSize.otherSize]">
                  <div v-else style="width:42px;height:18px;text-align:right;">{{curstomerDate.day}}</div>
                  <div>日</div>
                </div>
                <div class="input-label clearfix">
                  <div style="width:3.5em">地址：</div>
                  <show-textarea v-if="mode==='edit'" class="floor-input" style="width:calc(100% - 4em)" v-model="user.companyInfo.address" :autosize="true"
                    :style="[textSize.otherSize]"></show-textarea>
                  <div v-else class="floor-input" style="width:calc(100% - 4em)" :style="[textSize.otherSize]" v-html="formatShowData(user.companyInfo.address)"></div>
                </div>
                <div class="input-label clearfix">
                  <div style="width:3.5em">电话：</div>
                  <show-textarea v-if="mode==='edit'" class="floor-input" style="width:calc(100% - 4em)" v-model="user.companyInfo.phone" :autosize="true"
                    :style="[textSize.otherSize]"></show-textarea>
                  <div v-else class="floor-input" style="width:calc(100% - 4em)" :style="[textSize.otherSize]" v-html="formatShowData(user.companyInfo.phone)"></div>
                </div>
                <div class="input-label clearfix">
                  <div style="width:3.5em">传真：</div>
                  <show-textarea v-if="mode==='edit'" class="floor-input" style="width:calc(100% - 4em)" v-model="user.companyInfo.fax" :autosize="true"
                    :style="[textSize.otherSize]"></show-textarea>
                  <div v-else class="floor-input" style="width:calc(100% - 4em)" :style="[textSize.otherSize]" v-html="formatShowData(user.companyInfo.fax)"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  `;

  return {
    props: {
      orderType: {
        type: [Number, String],
        default: ''
      }
    },
    mixins: [printPurchaseOrderTemplMixin('purchaseOrder')],
    data: function () {
      return {
        orderGroups: [],
        groupFields: [],
        mergeFields: [],
        supplierDate: {
          year: '',
          month: '',
          day: ''
        },
        curstomerDate: {
          year: '',
          month: '',
          day: ''
        }
      };
    },
    methods: {
      print: function () {
        if (this.printOrderNo === '') {
          this.$alert('请输入采购单号', '信息');
          return;
        }

        this.loading = true;
        var self = this;
        this.changePrintType().then(function (flag) {
          if (!flag) {
            self.loading = false;
            return;
          }

          self.toPrintOrder('purchaseOrder');
        });
      },
      changePrintType: function () {
        var printOrders = this.printOrders;
        var printOrder = _.find(printOrders, {
          isPrint: 0
        });

        if (!this.deliveryEdit && printOrder === undefined) {
          return Promise.resolve(true);
        }

        var printOrderIds = [];
        for (var i = 0; i < printOrders.length; i++) {
          var ids = printOrders[i].printOrderIds;
          printOrderIds.pushArray(ids);
        }
        var postData = {
          ids: printOrderIds.join(','),
          type: this.orderType,
          isPrint: 1
        };
        if (this.deliveryEdit) {
          var deliveryTime = this.deliveryTime;
          if (deliveryTime !== null) {
            postData.laterPhaseOne = moment(deliveryTime).format('YYYY-MM-DD HH:mm:ss');
          }
        }

        var self = this;
        return ajaxRequest('order/updateBatchPurchaseOrderDetail', postData).then(function () {
          self.$emit('order-change', printOrder !== undefined);
          return true;
        }).catch(function () {
          return false;
        });
      },
      sendEmail: function () {
        var self = this;
        this.mode = 'print';

        this.loading = true;
        this.$nextTick(function () {
          self.getOrderImage(this.$refs['printArea'], 'purchaseOrder.png').then(function (imgUrl) {
            return self.toSendEmail(imgUrl).then(function () {
              self.loading = false;
              self.mode = 'edit';
            });
          }).catch(function () {
            self.loading = false;
            self.mode = 'edit';
          });
        });
      },
      toSendEmail: function (imgUrl) {
        var self = this;
        return ajaxCssFiles([
          "/purchaseOrder/mixins/orderPrint.css",
          "/vueSystem/components/css/vueEditor.css"
        ]).then(function (cssStyles) {
          var $print = $(self.$el).find('.print-area');
          $print = $print.clone();
          $print = $('<div id="app"></div>').append($print);
          var cssText = cssStyles.join('\n');
          var $html = $('<div></div>').append($print).append(`<style>${cssText}</style>`);
          return ajaxRequest('purchaseOrder/sendEmailOnPurchasePrint', {
            providerName: self.selectCurstomer.customerName,
            printHtml: $html.html(),
            remoteUrl: imgUrl,
            fileName: '采购单.png'
          }).then(function (msg) {
            self.$alert(msg, '信息');
            return msg;
          });
        });
      },
      getOrderGroup: function () {
        var printOrders = this.printOrders;
        var groupFields = this.groupFields;
        var orderGroup = {};
        if (groupFields.length > 0) {
          orderGroup = _.groupBy(printOrders, function (order) {
            var values = _.map(groupFields, function (field) {
              return order[field];
            });
            return values.join('_');
          });
        } else {
          orderGroup = _.groupBy(printOrders, 'printOrderId');
        }

        var orderGroups = [];
        var index = 1;
        for (var key in orderGroup) {
          var orders = orderGroup[key];
          for (var i = 0; i < orders.length; i++) {
            orders[i].index = index;
            index++;
          }
          var sum = _.sumBy(orders, 'purchaseCount');
          sum = _.round(sum, 4);
          var obj = {
            sum: sum,
            orders: orders
          };
          orderGroups.push(obj);
        }
        return orderGroups;
      },
      getMergeOrders: function (orderList) {
        var orderList = _.cloneDeep(orderList);

        var mergeFields = this.mergeFields;
        mergeFields.push('providerName');
        var orderGroup;
        if (mergeFields.length > 0) {
          orderGroup = _.groupBy(orderList, function (order) {
            var values = _.map(mergeFields, function (field) {
              return field + '--' + order[field];
            });
            return values.join('$#$');
          });
        } else {
          orderGroup = _.groupBy(orderList, 'printOrderId');
        }

        var orders = [];
        for (var key in orderGroup) {
          var orderGroups = orderGroup[key];
          var order = _.cloneDeep(orderGroups[0]);
          var ids = _.map(orderGroups, 'printOrderId');
          order.printOrderIds = ids;

          var purchaseCount = _.sumBy(orderGroups, 'purchaseCount');
          order.purchaseCount = _.round(purchaseCount, 4);

          if (order.hidePriceForPurchase === 1) {
            order.totalMoney = '';
          } else {
            var totalMoney = _.sumBy(orderGroups, 'totalMoney');
            order.totalMoney = _.round(totalMoney, 2);
          }

          var remarks = [];
          for (var i = 0; i < orderGroups.length; i++) {
            var orderObj = orderGroups[i];
            var remark = orderObj.remark;
            if (SysUtil.isEmpty(remark)) {
              remark = orderObj.feedOrderRemark;
            }

            if (!SysUtil.isEmpty(remark)) {
              remarks.push(remark);
            }
          }
          remarks = _.uniq(remarks);
          order.remark = remarks.join('\n');

          var obj = _.maxBy(orderGroups, 'maxLaterPhase');
          if (obj !== undefined) {
            order.maxLaterPhase = obj.maxLaterPhase;
          }

          var printOrder = _.find(orderGroups, {
            isPrint: 0
          });
          if (printOrder !== undefined) {
            order.isPrint = 0;
          } else {
            order.isPrint = 1;
          }
          orders.push(order);
        }
        return orders;
      },
      deleteRow: function (order) {
        var searchOrders = this.searchOrders;
        var index = _.findIndex(searchOrders, {
          printOrderId: order.printOrderId
        });
        if (index === -1) {
          return;
        }
        searchOrders.splice(index, 1);
        this.sortData();
        this.orderGroups = this.getOrderGroup();
      },
      formatShowData: function (text) {
        if (SysUtil.isEmpty(text)) {
          text = '';
        }
        var htmlText = text.replace(/ /g, '&nbsp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>');
        return htmlText;
      }
    },
    template: template
  };
}();
